package com.huimingpay.merchant.service.impl;

import com.alibaba.fastjson.JSON;
import com.huimingpay.common.domain.BusinessException;
import com.huimingpay.common.domain.CommonErrorCode;
import com.huimingpay.merchant.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service //普通Service 并非发布Dubbo服务
@Slf4j
public class SmsServiceImpl implements SmsService {
    @Value("${sms.url}")
    String baseUrl;

    @Value("${sms.effectiveTime}")
    String effectiveTime;

    @Resource
    RestTemplate restTemplate;

    /**
     * 发送手机验证码
     *
     * @param phone 手机号
     * @return 验证码对应的key
     */
    @Override
    public String sendSms(String phone) {
        //设置向验证码服务发送请求的地址
        String sms_url = baseUrl + "/generate?name=sms&effectiveTime=" + effectiveTime;

        //写请求体
        HashMap<String, Object> body = new HashMap<>();
        body.put("mobile", phone);

        //请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        //指定Content-Type: application/json
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);

        //请求信息,传入body，header
        HttpEntity httpEntity = new HttpEntity(body, httpHeaders);

        //发送请求
        ResponseEntity<Map> exchange = null;
        Map bodyMap = null;

        try {
            // 发送请求
            exchange = restTemplate.exchange(sms_url, HttpMethod.POST, httpEntity, Map.class);
            log.info("请求验证码服务，得到响应：{}", JSON.toJSONString(exchange));

            //获取响应体
            bodyMap = exchange.getBody();
        } catch (RestClientException e) {
            e.printStackTrace();
            log.error("请求验证码服务失败，原因：{}", e);
        }

        // 如果响应体为空或结果为空，则抛出异常
        if (bodyMap == null || bodyMap.get("result") == null) {
            throw new RuntimeException("发送验证码失败");
        }

        // 提取结果中的key
        Map result = (Map) bodyMap.get("result");
        String key = (String) result.get("key");
        log.info("得到发送验证码对应的key:{}", key);
        return key;


    }

    /**
     * 校验验证码
     *
     * @param verifyKey  验证码key
     * @param verifyCode 验证码
     */
    @Override
    public void checkVerifyCode(String verifyKey, String verifyCode) {
        //http://localhost:56085/sms/verify?name=sms&verificationCode=142424&verificationKey=6466636
        String url = baseUrl + "/verify?name=sms&verificationCode=" + verifyCode + "&verificationKey=" + verifyKey;

        Map responseMap = null;
        try {
            // 发送请求
            ResponseEntity<Map> exchange = restTemplate.exchange(url, HttpMethod.POST, HttpEntity.EMPTY, Map.class);
            responseMap = exchange.getBody();
            log.info("请求验证码服务，得到响应：{}", JSON.toJSONString(responseMap));
        } catch (RestClientException e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            //throw new RuntimeException("验证码校验失败"); 采用自定义异常
            throw new BusinessException(CommonErrorCode.E_100102);
        }

        // 如果响应体为空或结果为空，则抛出异常
        if (responseMap == null || responseMap.get("result") == null || !(Boolean)responseMap.get("result")) {
            //throw new RuntimeException("验证码校验失败"); 采用自定义异常
            throw new BusinessException(CommonErrorCode.E_100102);
        }
    }

}
